package com.roy.netty.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

/**
 * @author ：楼兰
 * @date ：Created in 2021/6/8
 * @description:
 **/

public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    //Netty提供的组件，按照<ChannelID,Channel>的格式缓存连接
//    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static ChannelService channelService = new ChannelService();
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("服务器收到消息："+msg.text());
        final TextWebSocketFrame response = new TextWebSocketFrame("服务器时间" + LocalDateTime.now() + ",客户端"+ctx.channel().id()+"，发送消息：" + msg.text());
//        ctx.channel().writeAndFlush(response);
        channelService.broadCast(response);
//        channelGroup.writeAndFlush(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常："+cause.getMessage());
        channelService.closeChannel(ctx.channel());
//        channelGroup.remove(ctx.channel());
//        ctx.close();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        channelService.addChannel(ctx.channel());
//        channelGroup.add(ctx.channel());
        System.out.println("连接添加：短ID= "+ctx.channel().id().asShortText());
        System.out.println("连接添加：长ID= "+ctx.channel().id().asLongText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
//        channelGroup.remove(ctx.channel());
        channelService.closeChannel(ctx.channel());
        System.out.println("断开连接：短ID= "+ctx.channel().id().asShortText());
    }
}
